package com.zsq.thread.test1;

/**
 * @author : zhang sq
 * @date : 2019/12/25 20:42
 **/
//线程的方法
public class ThreadMethod {

    public static void main(String[] args) {
        //testSleep();
        //testVield();
        testJoin();
    }

    //休眠500毫秒  休眠完后就绪
    static void testSleep(){
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                System.out.println("A"+i);
                try {
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //回到就绪 换其他线程执行  也可能再次被选中(低概率)
    static void testVield(){
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                System.out.println("A"+i);
               if(i%10==0) Thread.yield();
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                System.out.println("B"+i);
                if(i%10==0) Thread.yield();
            }
        }).start();
    }

    //加入线程优先执行完
    // 例:线程 t2里面调用  t1.join() 表示t1优先执行完再执行t2
    static void testJoin(){
        Thread t1=new Thread(()->{
            for (int i = 0; i < 100; i++) {
                System.out.println("A"+i);
                try {
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        Thread t2=new Thread(()->{
            System.out.println(123);
                try {
                    t1.join();
                    Thread.sleep(500);
                    System.out.println(321);
                }catch (Exception e){
                    e.printStackTrace();
                }

        });
        t1.start();
        t2.start();
    }
}
